<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Capsule\Manager;
use Illuminate\Support\Facades\Config;
use Session;
use DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Log;
use App\Http\Requests\CreateRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use App\Roles;
use App\Permission;
use App\AdminMenu;
use App\RoleMenu;
use Illuminate\Support\Facades\Auth;


class RolesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function index(Request $request) {
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);

		$roles = Roles::where('is_del',1)->get();
		$data['roles'] = $roles;
//		dd($data['optionArr']);
		return view('roles.list')->with($data);
	}

	public function create()
	{

		// 所有菜单
		$data['menus'] = AdminMenu::getAllMenuTitle();
		// 所有菜单的option
		$data['menuOption'] = AdminMenu::getMenuOptionName();

		return view('roles.create')->with($data);
	}

    public function store(CreateRoleRequest $request){
//        Log::info(__FILE__.__LINE__."新增数据保持");
        DB::beginTransaction();
        $roles = new Roles();
        $roles->role_name =$request->role_name;
        $roles->slug =$request->slug;

	    $menuPermission = $request->menuPermission ;
	    $menuOptions = $request->menuOptions;
        if($roles->save()){
	        if($menuPermission && $menuOptions ){
		        // 保存新的权限
		        foreach ($menuPermission as $key=>$value){
			        $roleMenu = new RoleMenu();
			        $roleMenu->role_id = $roles->id;
			        foreach($menuOptions as $kk=>$vv){
				        if($value == $kk){
					        $roleMenu->option_ids  = implode(',',$vv);
				        }
			        }
			        $roleMenu->menu_id  = $value;
			        $roleMenu->save();
		        }
	        }

            DB::commit();

	        $adminUser = Auth::user();
	        if($adminUser){
		        $userId = $adminUser->id;
		        $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'新增了【 '.$request->role_name.' 】角色';
		        adminOperationLog($request,$userId,$logs);
	        }

            return redirect('roles/list')->with('success','新增成功');
        }else{
            DB::rollback();
            return redirect()->back()->withInput();
        }
    }

	public function edit($id)
	{
		// 角色信息
		$data['rolesInfo'] = Roles::find($id);
		// 所有菜单
		$data['menus'] = AdminMenu::getAllMenuTitle();
		// 角色已有的菜单
		$data['roleMenus'] = Roles::getMenuRoles($id);
		// 所有菜单的option
		$data['menuOption'] = AdminMenu::getMenuOptionName();
//		dd($data['roleMenus']);

		return view('roles.edit')->with($data);

	}

    public function update(UpdateRoleRequest $request, $id){

//    	dd($request->menuPermission);

        DB::beginTransaction();
        $roles = Roles::find($id);
        $roles->role_name =$request->role_name;
        $roles->slug =$request->slug;
        $role_id =$request->role_id;

        if(!$roles->save()){
            DB::rollback();
            return Redirect::back()->withInput()->withErrors(['fail' => trans('message.updateFail')]);
        }
	// 保存权限
	    $menuPermission = $request->menuPermission ;
	    $menuOptions = $request->menuOptions;

//	    echo '<pre>';
//	    print_r($menuPermission);
//	    print_r($menuOptions);
//	    exit;

	    if($menuPermission  ){
		    // 获取当前角色的所有权限，如果有，删除原来的权限，保存新的权限
		    if(RoleMenu::getRoleMenuId($role_id)){
			    RoleMenu::where('role_id',$role_id)->delete();
		    }
		    // 保存新的权限
		    foreach ($menuPermission as $key=>$value){
			    $roleMenu = new RoleMenu();
			    $roleMenu->role_id = $roles->id;
			    if($menuOptions){
				    foreach($menuOptions as $kk=>$vv){
					    if($value == $kk){
						    $roleMenu->option_ids  = implode(',',$vv);
					    }
				    }
			    }
			    $roleMenu->menu_id  = $value;
			    $roleMenu->save();
		    }
	    }

        DB::commit();

	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'编辑了【 '.$request->role_name.' 】角色';
		    adminOperationLog($request,$userId,$logs);
	    }

        return Redirect::to(url('roles/list'))->with('success', trans('message.updateSuccess'));

    }


	public function delete(Request $request)
	{
		$uid = $request->id;
        if(!$uid){
            return '-1';
        }
		$name = Roles::getNameById($uid);


        DB::beginTransaction();

        //  del
		$affectId= Roles::where('id',$uid)->update([
			'is_del'=>-1
		]);
//        $affectId = Roles::where('id',$request->id)->delete();
        if(!$affectId){
            DB::rollback();
            return -1;
        }
		// 删除角色对应的用户
		UserRole::where('role_id',$uid)->delete();
		// 删除角色对应的菜单
		RoleMenu::where('role_id',$uid)->delete();

        DB::commit();


		$adminUser = Auth::user();
		if($adminUser){
			$userId = $adminUser->id;
			$logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'删除了【 '.$name.' 】角色';
			adminOperationLog($request,$userId,$logs);
		}


        return 1;
	}
}





